package com.zjc.gateway.exception;

import com.zjc.gateway.constants.AppExcCodesEnum;
import com.zjc.gateway.constants.GenericResultDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 全局异常拦截
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxUploadSize;

    /**
     * 文件大小超出限制异常拦截
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MaxUploadSizeExceededException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public GenericResultDto sizeLimitExceededException(Exception e) {
        log.info("上传的文件大小超出允许值{}", this.maxUploadSize, e);
        return GenericResultDto.fail(AppExcCodesEnum.FILE_SIZE_LIMIT_EXCEEDED.getCode(), AppExcCodesEnum.FILE_SIZE_LIMIT_EXCEEDED.getMessage() + this.maxUploadSize);
    }

    /**
     * 全局异常.
     *
     * @param e the e
     * @return the wrapper
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public GenericResultDto exception(Exception e) {
        log.info("保存全局异常信息 ex={}", e.getMessage(), e);
        return GenericResultDto.fail(AppExcCodesEnum.OPERATE_FAIL);
    }
}
